<template>
  <!-- 盘点任务表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="700"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="110"
      >
        <h4 class="mb-[20px] mt-[0px]">基本信息</h4>
        <div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="任务名称" prop="orderName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.orderName"
                  placeholder="请输入任务名称"
                  clearable
                  style="width: 250px"
                />
                <span v-else>{{ formData.orderName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="仓库" prop="warehouseId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.warehouseId"
                  clearable
                  placeholder="请选择仓库"
                  @change="warehouseChange"
                  style="width: 250px"
                >
                  <el-option
                    v-for="item in warehouses"
                    :key="item.id"
                    :label="item.warehouseCode + '：' + item.warehouseName"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.warehouseName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="仓位">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.binId"
                  clearable
                  :disabled="props.isReadonly ? true : false"
                  placeholder="请选择仓位"
                  @change="binChange"
                  style="width: 250px"
                  filterable
                  :filter-method="handleFilter"
                >
                  <el-option
                    v-for="item in bins"
                    :key="item.id"
                    :label="item.binCode + '：' + item.binName"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.binName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="盘点日期" prop="inventoryDate">
                <el-date-picker
                  v-if="!props.isReadonly"
                  v-model="formData.inventoryDate"
                  type="date"
                  :disabled-date="disabledDate"
                  align="right"
                  style="width: 250px"
                />
                <span v-else>{{ formData.inventoryDate }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">物料信息</h4>

        <el-card shadow="never" class="table-container">
          <template v-if="!props.isReadonly" #header>
            <el-button type="success" plain @click="openDialogAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />

              <el-table-column
                label="物料编码"
                prop="materialCode"
                min-width="100"
              />
              <el-table-column
                label="物料名称"
                prop="materialName"
                min-width="110"
                header-align="center"
              />
              <!-- <el-table-column
                label="存储批次"
                prop="stockBatch"
                min-width="110"
              />
              <el-table-column
                label="包装编号"
                prop="storageCode"
                min-width="110"
              /> -->
              <!-- <el-table-column
                label="数量"
                prop="availableQuantity"
                align="center"
              /> -->
              <!--
              <el-table-column
                label="数量单位"
                prop="quantityUnit"
                align="center"
              >
                <template #default="scope">
                  {{ useDictionary("MeasurementUnit", scope.row.quantityUnit) }}
                </template>
              </el-table-column> -->

              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="80"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <searchMaterialDialog
      v-model:visible="addDialog.visible"
      :title="addDialog.title"
      :isMultiple="true"
      :data="addDialog.data"
      :is-readonly="addDialog.readvisible"
      @echo-info="getSelect"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "WMSWMSINVENTORYTASKADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  warehouseId: "",
  warehouseCode: "",
  warehouseName: "",
  orderName: "",
  binId: "",
  binCode: "",
  binName: "",
  inventoryDate: "",
  details: [], // 初始化为空数组，不包含默认数据
});

/** rules规则 */
const rules = reactive({
  orderName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  materialId: "",
  materialCode: "",
  materialName: ""
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    if (newVal && Object.keys(newVal).length > 0) {
      // 清空现有数据
      Object.keys(formData).forEach(key => {
        if (key !== 'details') {
          formData[key] = '';
        }
      });
      formData.details = [];
      
      // 赋值新数据
      Object.assign(formData, newVal);
    }
  },
  { immediate: true, deep: true }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = []; // 重置为空数组，不添加空数据
  formData.orderName = "";
  formData.warehouseId = "";
  formData.warehouseCode = "";
  formData.warehouseName = "";
  formData.binId = "";
  formData.binCode = "";
  formData.binName = "";
}

const loading = ref(false);


onMounted(() => {
  getWarehouses();
  if (formData.binId) {
    getbin();
  }
});

/** 盘点任务保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/wms/inventoryTask/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

// async function getdetails() {
//   let sondetails = await request({
//     url: "/wms/inventoryTask/getDetails",
//     method: "post",
//     data: formData,
//   }).finally(() => {
//     loading.value = false;
//   });
//   formData.details = sondetails.data;
// }

//查询仓库列表
let warehouses = ref([]);
async function getWarehouses() {
  const data = await request({
    url: "/wms/wmswarehouse/getOptionList",
    method: "post",
    data: { deleted: 0 },
  });
  warehouses.value = data.data;
}

let bins = ref([]);
//查询仓位列表
async function getbin() {
  const data = await request({
    url: "/wms/wmsbin/getOptionList",
    method: "post",
    data: {
      warehouseId: formData.warehouseId,
    },
  });
  bins.value = data.data;
}

function binChange(id: string) {
  formData.details = [];
  if (id) {
    var bin = bins.value.find((item) => {
      return item.id === id;
    });
    if (bin) {
      formData.binCode = bin.binCode;
      formData.binName = bin.binName;
    }
  }
}

function handleFilter(val: string) {
  if (val && val.trim() !== '') {
    formData.binName = val;
    getbin();
  }
}

function warehouseChange(id: string) {
  formData.details = []; // 清空物料列表
  formData.binId = "";
  formData.binCode = "";
  formData.binName = "";

  if (id) {
    var warehouse = warehouses.value.find((item) => {
      return item.id === formData.warehouseId;
    });
    formData.warehouseCode = warehouse.warehouseCode;
    formData.warehouseName = warehouse.warehouseName;
    getbin();
  }
}


const addDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  data: [],
});
function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

/** 打开外协发货单表单弹窗 */
function openDialogAdd() {
  addDialog.title = "库存选择";
  addDialog.data = formData;
  addDialog.visible = true;
}

function getSelect(options: any) {
  //console.log(options);
  formData.details = [];
  for (const value of options) {
    console.log(value); // 输出: 1, 2, 3
    formData.details.push(value);
  }

  //formData.details = options;
}

const disabledDate = (time: Date) => {
  const now = new Date();
  return (
    time.getTime() <
    new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
  );
};

</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
